package com.losl.framework.controller;

import cn.hutool.captcha.*;
import cn.hutool.core.util.IdUtil;
import com.losl.common.constant.Constant;
import com.losl.common.core.domain.Result;
import com.losl.common.core.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 验证码
 *
 * @author Maxwell
 */
@RestController
@Api(value = "验证码-API",tags = {"验证码相关接口"})
public class CaptchaController {
    @Autowired
    private RedisCache redisCache;

    /**
     * 验证码生成
     */
    @ApiOperation("获取验证码,登陆系统的第一步就是请求验证码")
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request) {
        //用户唯一标识
        String uuid = IdUtil.simpleUUID();
        String vertifykey= Constant.CAPTCHA_CODE_KEY+uuid;

        //验证码
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 40, 4,2);
        captcha.createCode();
        String code = captcha.getCode();
        System.out.println(code);

        //将验证码和用户标识存入redis中
        redisCache.setCacheObject(vertifykey,code,Constant.CAPTCHA_EXPIRETION, TimeUnit.MINUTES);

        Result result = Result.success();
        result.put("uuid",uuid);
        result.put("img", captcha.getImageBase64());
        return result;
    }

}
